package com.copa.client;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.util.Iterator;
import java.util.Set;

/**
 * @author copa
 * @createDate 2021-09-23 9:30
 * @function
 */
public class ClientThread implements Runnable{

    private Selector selector;

    public ClientThread(Selector selector) {
        this.selector = selector;
    }

    @Override
    public void run() {
        try {
            while (true) {
                // 若无连接可用，则不往下执行
                if (selector.select() == 0) {
                    continue;
                }
                Set<SelectionKey> selectionKeySet = selector.selectedKeys();
                Iterator<SelectionKey> iterator = selectionKeySet.iterator();
                while (iterator.hasNext()) {
                    SelectionKey selectionKey = iterator.next();
                    if (selectionKey.isReadable()) {
                        SocketChannel socketChannel = (SocketChannel) selectionKey.channel();
                        ByteBuffer buffer = ByteBuffer.allocate(1024);
                        int readLength = 0;
                        try {
                            readLength = socketChannel.read(buffer);
                        } catch (IOException e) {
                            // 服务器宕机
                            System.out.println("服务器宕机");
                            break;
                        }

                        String message = "";
                        if (readLength > 0) {
                            buffer.flip();
                            message += Charset.forName("UTF-8").decode(buffer);
                        }
                        socketChannel.register(selector, SelectionKey.OP_READ);
                        if (message.length() > 0) {
                            System.out.println(message);
                        }
                    }
                    iterator.remove();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
